<?php
namespace Home\Controller;
use Lib\Api\AgentApi;
use Lib\Api\AgentBelongApi;
use Lib\Api\OrganizationApi;
use Lib\Api\OrganizationBelongApi;
use Lib\Api\OrganizationSettingApi;
use Lib\Api\SysApi;
use Lib\Api\UserApi;
use Lib\Api\UserBelongApi;
use Lib\Api\WxInfoApi;
use Lib\Utils\Utils;
use Think\Controller;
class Oauth2Controller extends Controller {

    private $token = 'weixin';
    public function token() {
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }

        $echostr = $_GET['echostr'];
        if (!empty($echostr)) {
            $nonce     = $_GET['nonce'];
            $timestamp = $_GET['timestamp'];
            $signature = $_GET['signature'];
            $this->valid($echostr, $signature, $nonce, $timestamp);
        } else {
            $OrgNo = $_GET['OrgNo'];
            $access_token = $this->getAccess_token($OrgNo);

            /*$path = "C:/HwsApacheMaster/wwwroot/sdsfds_zEwnml/log/wx/";
            if (!is_dir($path)){
                mkdir($path,0777);  // 创建文件夹test,并给777的权限（所有权限）
            }
            $file = $path.'wx_info.txt';    // 写入的文件
            $log = "access_token：".$access_token;
            file_put_contents($file,$log,FILE_APPEND);*/

            // 创建自定义菜单
            /*$menu = $this->get_menu($access_token);
            if (empty($menu)) {
                $this->create_menu($access_token, $OrgNo);
            }*/


            // $this->create_menu($access_token, $OrgNo);

            $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = (string)$postObj->FromUserName;
            $Event = (string)$postObj->Event;

            if ($Event == "subscribe") {
                // $keyArray = array();
                $invite_code = "";
                if (!empty($postObj->EventKey)) {
                    $EventKey = (string)$postObj->EventKey;
                    $keyArray = explode("_", $EventKey);
                    $invite_code = $keyArray[1];
                }
				session("invite_code", $invite_code);
                $this->registorlogin($access_token, $fromUsername, $invite_code, $OrgNo, 1);
                /*if (count($keyArray) == 1) {
                    //已关注者扫描
                } else {
                    //未关注者关注后推送事件
                }*/
            }
        }
    }

    // 微信授权
    public function index() {
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }


        if (empty($_GET['organization_code'])) {
            exit("错误的机构码");
        }
        session("organization_code", null);

        $organization_code = $_GET['organization_code'];
        $where['_string'] = "concat(b.p_code,b.level,b.code)='".$organization_code."'";
        $left = "left join fs_organization b on b.id = a.organization_id and a.state = 1";
        $organizationSetting = OrganizationSettingApi::getInfoByCondition($where, $left, "a.wx_appid");
        $APPID=$organizationSetting['wx_appid'];

        $domain_url = C('TMPL_PARSE_STRING.__DOMAINURL__');
        $web_site_dir = C('TMPL_PARSE_STRING.__WEBSITEDIR__');
        $REDIRECT_URI=$domain_url.$web_site_dir.'/Oauth2/callback?organization_code='.$organization_code;
        // $scope='snsapi_base';
        $scope='snsapi_userinfo';//需要授权
        $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$APPID.'&redirect_uri='.urlencode($REDIRECT_URI).'&response_type=code&scope='.$scope.'&connect_redirect=1&state=STATE#wechat_redirect';
        // $this->display($url);
        header("Location:$url");
    }

    // 生成二维码
    public function wx_qrcode() {
        if (!empty(session("user_id")) && !empty(session("organization_code"))) {
            $user_id = session("user_id");
            $user = AgentApi::getInfo(array("b.id"=>$user_id), "left join fs_user b on b.agent_id = a.id", "a.id, a.state, a.ticket, b.code");
            if ($user['state'] == 1) {
				$ticket_url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=';
				if (empty($user['ticket'])) {
					$access_token = $this->getAccess_token(session("organization_code"));
					$url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;
					$qrcode = '{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": '.$user['code'].'}}}';
					$result = $this->api_notice_increment($url, $qrcode);
					$result = json_decode($result, true);
					$ticket_url = $ticket_url.urlencode($result['ticket']);
					AgentApi::saveByCondition(array("id"=>$user['id']), array("ticket"=>$result['ticket']));
				} else {
					$ticket_url = $ticket_url.urlencode($user['ticket']);
				}
                header("Location:$ticket_url");
            } else {
                exit;
            }
        }
    }

    // 生成二维码
    public function user_wx_qrcode($user_id) {
        $AGENTCONFIG = C('AGENTCONFIG');
        $level = 0;
        for ($i=0; $i<count($AGENTCONFIG); $i++) {
            if ($AGENTCONFIG[$i]['type'] == 'dl') {
                $level = $AGENTCONFIG[$i]['level'];
                break;
            }
        }
        $map['a.user_id'] = $user_id;
        $map['a.organization_level'] = $level;
        $map['DATE_FORMAT(a.datetime, "%Y-%m-%d %H:%i:%s")'] = array('elt', 'DATE_FORMAT("'.date('Y-m-d H:i:s').'", "%Y-%m-%d %H:%i:%s")');
        $left = "left join fs_organization b on b.id = a.organization_id";
        $belongOrg = UserBelongApi::getUserBelongOrgByCondition($map, $left, "concat(b.p_code,b.level,b.code) as code");

        if (!empty($belongOrg)) {
            $user = AgentApi::getInfo(array("b.id"=>$user_id), "left join fs_user b on b.agent_id = a.id", "a.id, a.state, a.ticket, b.code");
            if ($user['state'] == 1) {
				$ticket_url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=';
				if (empty($user['ticket'])) {
					$access_token = $this->getAccess_token($belongOrg["code"]);
					$url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;
					// var_dump($user['code']);
					$qrcode = '{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": '.$user['code'].'}}}';
					$result = $this->api_notice_increment($url, $qrcode);
					$result = json_decode($result, true);
					$ticket_url = $ticket_url.urlencode($result['ticket']);
					AgentApi::saveByCondition(array("id"=>$user['id']), array("ticket"=>$result['ticket']));
				} else {
					$ticket_url = $ticket_url.urlencode($user['ticket']);
				}
                header("Location:$ticket_url");
            } else {
                exit;
            }
        } else {
            var_dump("没有机构");
        }
    }

    // 回调方法
    public function callback() {
        $organization_code = $_GET['organization_code'];
        $code = $_GET['code'];

        $appid="";
        $appsecret="";
        $access_token = $this->getAccess_token($organization_code, $appid, $appsecret);
        $openid = $this->getOpenid($appid, $appsecret, $code);
        $user_id = $this->registorlogin($access_token, $openid, session("invite_code"), $organization_code, 2);

        $user['login_num'] = array('exp','login_num+1');
        $user['last_login'] = date('Y-m-d H:i:s');
        $user['login_ip'] = getenv('REMOTE_ADDR');
        UserApi::saveByCondition(array("id"=>$user_id), $user);

        session("user_id", $user_id);
        session("organization_code", $organization_code);
        
		$user = UserApi::getInfo(array("id"=>$user_id), "state");
        if ($user["state"] == 1) {
            // $this->display("shopping/index");
            $domain_url = C('TMPL_PARSE_STRING.__DOMAINURL__');
            $web_site_dir = C('TMPL_PARSE_STRING.__WEBSITEDIR__');
            header("Location:".$domain_url.$web_site_dir."/shopping/index");
        } else {
            $domain_url = C('TMPL_PARSE_STRING.__DOMAINURL__');
            $web_site_dir = C('TMPL_PARSE_STRING.__WEBSITEDIR__');
            header("Location:".$domain_url.$web_site_dir."/index");
        }
    }

    // 获取扫码标签
    public function getSignture() {
        $appid="";
        $access_token = $this->getAccess_token(session("organization_code"), $appid);

        $jsapi_ticket = $this->getJsApiTicket($access_token);
        // $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $url = $_GET['urls'];
        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array(
            "appId"     => $appid,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        $this->ajaxReturn($signPackage);
    }

    // 添加新关注者信息或微信登录
    private function registorlogin($access_token, $openid, $invite_code, $organization_code, $s) {
		
		$path = "C:/HwsApacheMaster/wwwroot/400tcc_xzRyaq/log/wx/";
        if (!is_dir($path)){
            mkdir($path,0777);  // 创建文件夹test,并给777的权限（所有权限）
        }
        $file = $path.'wx_info.txt';    // 写入的文件
		
        $wx_info = WxInfoApi::getInfo(array("openid"=>$openid));
        if (empty($wx_info)) {
            $user_info_res = json_decode($this->getUserInfo($access_token, $openid), true);
            if (!isset($user_info_res["errcode"])) {
                $wx_info['subscribe'] = $user_info_res["subscribe"];
                $wx_info['openid'] = $user_info_res["openid"];
                $wx_info['nickname'] = Utils::userTextEncode($user_info_res["nickname"]);
                $wx_info['sex'] = $user_info_res["sex"];
                $wx_info['city'] = $user_info_res["city"];
                $wx_info['country'] = $user_info_res["country"];
                $wx_info['province'] = $user_info_res["province"];
                $wx_info['language'] = $user_info_res["language"];
                $wx_info['headimgurl'] = $user_info_res["headimgurl"];
                $wx_info['subscribe_time'] = $user_info_res["subscribe_time"];
                $wx_info['remark'] = $user_info_res["remark"];
                $wx_info['groupid'] = $user_info_res["groupid"];
                $wx_info['datetime'] = date('Y-m-d H:i:s');
                $wx_id = WxInfoApi::add($wx_info);
            } else {
                exit(" 错误");
            }
        } else {
            $wx_id = $wx_info['id'];
        }

        $left = "left join fs_user_belong b on b.user_id = a.id left join fs_organization c on c.id = b.organization_id";
        $where['_string'] = "a.wx_id = ".$wx_id." and concat(c.p_code,c.level,c.code)='".$organization_code."'";
        $user = UserApi::getInfoByCondition($where, $left, "a.id, a.nick_name, a.password");

        if (empty($user)) {
			$s_str = "非关注进入";
			if ($s == 1) {
				$s_str = "关注二维码进入";
			}
			$log = "新用户注册,".$s_str."，open_id：".$openid."，邀请码：".$invite_code."，机构编码：".$organization_code;
            file_put_contents($file,$log,FILE_APPEND);
			
            // 注册一个新的用户
            $recommend_id = 0;
            if ($invite_code != "") {
                // 获取经纪人ID
                $recommend_left = "left join fs_user b on b.agent_id = a.id";
                $recommend_user = AgentApi::getInfo(array('b.code'=>$invite_code), $recommend_left, 'a.id');
                if (!empty($recommend_user)) {
                    $recommend_id = $recommend_user['id'];
                } else {
                    $log = "\r\n注册失败，邀请码错误";
                    $log .= "\r\n--------------------------------------------------------------------------------------------------\r\n";
                    file_put_contents($file,$log,FILE_APPEND);
                    exit;
                }
            }

            $organization_id = 0;
            $organization_level= 0;
            if ($recommend_id == 0) {
                if ($organization_code != "") {
                    // 获取机构信息
                    $where['_string'] = "concat(p_code,level,code)='".$organization_code."'";
                    $organization = OrganizationApi::getInfo($where, "a.id, a.level");
                    if (!empty($organization)) {
                        $organization_id = $organization['id'];
                        $organization_level = $organization['level'];
                    } else {
                        $log = "\r\n注册失败，机构编码错误";
                        $log .= "\r\n--------------------------------------------------------------------------------------------------\r\n";
                        file_put_contents($file,$log,FILE_APPEND);
                        exit;
                    }
                }
            } else {
                $organization_list = AgentBelongApi::getAllUserBelongList(array("a.agent_id"=>$recommend_id, "a.state"=>1), "left join fs_organization b on b.id = a.organization_id", "b.id, b.level", "a.organization_level desc");
                if (!empty($organization_list)) {
                    $organization_id = $organization_list[0]['id'];
                    $organization_level = $organization_list[0]['level'];
                } else {
                    $log = "\r\n注册失败，获取不到推荐经纪人归属";
                    $log .= "\r\n--------------------------------------------------------------------------------------------------\r\n";
                    file_put_contents($file,$log,FILE_APPEND);
                    exit;
                }
            }

            /*$path = "C:/HwsApacheMaster/wwwroot/sdsfds_zEwnml/log/wx/";
            if (!is_dir($path)){
                mkdir($path,0777);  // 创建文件夹test,并给777的权限（所有权限）
            }
            $file = $path.'wx_info.txt';    // 写入的文件
            $log = "推荐人ID：".$recommend_id;
            file_put_contents($file,$log,FILE_APPEND);*/

            $user['nick_name'] = $wx_info["nickname"];
            $user['sex'] = $wx_info["sex"];
            $user['photo_url'] = $wx_info["headimgurl"];
            $user['district'] = $wx_info["city"];
            $user['agent_id'] = 0;
            $user['recommend_id'] = $recommend_id;
            $user['type'] = 1;
            $user['state'] = 0;
            $user['wx_id'] = $wx_id;
            $user['freeze_balance'] = 0;
            $user['balance'] = 0;
            $user['integral'] = 0;
            $user['use_voucher_num'] = 0;
            $user['source'] = 1;
            $user['login_num'] = 0;
            $user['code'] = $this->generate_invite_code(999999);
            $user['datetime'] = date('Y-m-d H:i:s');
			$user['is_deall_order'] = 1;
			$user['recharge'] = 0;
            $user['withdrawals'] = 0;
            $id = UserApi::add($user);
            if ($id > 0) {
				$log = "\r\n注册成功-用户ID：".$id;
                $log .= "\r\n--------------------------------------------------------------------------------------------------\r\n";
                file_put_contents($file,$log,FILE_APPEND);
				
                // 添加用户归属
                if ($organization_id > 0) {
                    $user_belong_arr = array();
                    $organization_belong_list = OrganizationBelongApi::getAllList(array("organization_id"=>$organization_id));
                    if (count($organization_belong_list) > 0) {
                        for ($i=0; $i<count($organization_belong_list); $i++) {
                            $user_belong['user_id'] = $id;
                            $user_belong['organization_id'] = $organization_belong_list[$i]['belong_organization_id'];
                            $user_belong['organization_level'] = $organization_belong_list[$i]['belong_organization_level'];
                            $user_belong["state"] = 1;
                            $user_belong['datetime'] = date('Y-m-d H:i:s');
                            array_push($user_belong_arr, $user_belong);
                        }
                    }

                    $user_belong['user_id'] = $id;
                    $user_belong['organization_id'] = $organization_id;
                    $user_belong['organization_level'] = $organization_level;
                    $user_belong["state"] = 1;
                    $user_belong['datetime'] = date('Y-m-d H:i:s');
                    array_push($user_belong_arr, $user_belong);
                    if (count($user_belong_arr) > 0) {
                        UserBelongApi::addAll($user_belong_arr);
                    }
                }

                $sys = SysApi::getInfo(array("id"=>1), "is_send_voucher");
                $voucher_num = 0;
                if ($sys['is_send_voucher'] == 1) {
                    // 生成相应代金淃
                    $voucher_config_model = M('UserVoucherConfig');
                    $voucher_config_list = $voucher_config_model->select();
                    if (!empty($voucher_config_list)) {
                        for ($i=0; $i<count($voucher_config_list); $i++) {
                            for ($j=0; $j<$voucher_config_list[$i]['voucher_num']; $j++) {
                                $voucher_num++;
                                $number = "";
                                // 后期需要进行数据库查询判断
                                for ($z=0;$z<4;$z++) {
                                    if($z > 0) {
                                        $number = $number."-";
                                    }
                                    $number = $number.rand_number();
                                }

                                $voucher_range = $voucher_config_list[$i]['voucher_range'];
                                $day_num = $voucher_config_list[$i]['day_num'];
                                $start_date = date('Y-m-d');
                                $end_date = date('Y-m-d',strtotime("$start_date +$day_num day"));
                                $dataList[] = array(
                                    'user_id' => $id,
                                    'voucher_range' => $voucher_range,
                                    'number' => $number,
                                    'money' => $voucher_config_list[$i]['money'],
                                    'type' => $voucher_config_list[$i]['type'],
                                    'state' => 2,
                                    'source' => 1,
                                    'start_date' => $start_date,
                                    'end_date' => $end_date,
                                    'datetime' => date('Y-m-d H:i:s')
                                );
                            }
                        }
                        if (!empty($dataList)) {
                            $model = M('Voucher');
                            $model->addAll($dataList);
                        }
                    }
                }
            }
        } else {
            $id = $user['id'];
            if (empty($user['password'])) {
                session("set_password", 0);
            } else {
                session("set_password", 1);
            }

            // $user_info_res = json_decode($this->getUserInfo($access_token, $openid), true);
            // $user['nick_name'] = Utils::userTextEncode($user_info_res["nickname"]); //$this->userTextEncode($user_info_res["nickname"]);
            // UserApi::saveByCondition(array("id"=>$id), $user);

            // session('user_id', $user['id']);
        }
        return $id;
    }

    // 获取自定菜单
    private function get_menu($access_token) {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$access_token;
        $res = $this->https_request($url);
        $menu = json_decode($res, true);
        return $menu['menu'];
    }
    // 创建自定义菜单
    public function create_menu($organization_code, $appid) {
        $access_token = $this->getAccess_token($organization_code);
		
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
        $domain_url = C('TMPL_PARSE_STRING.__DOMAINURL__');
        $web_site_dir = C('TMPL_PARSE_STRING.__WEBSITEDIR__');
		$shopping = C('TMPL_PARSE_STRING.__SHOPPING__');
		
       /* $data = '{"button":[{"name":"交易指南","sub_button":[
        {"type":"view","name":"注册流程","url":"'.$WEBSITEDIR.'/gz/zhuce.jpg"},
        {"type":"view","name":"提现流程","url":"'.$WEBSITEDIR.'/gz/tixian.jpg"},
        {"type":"view","name":"充值流程","url":"'.$WEBSITEDIR.'/gz/chongzhi.jpg"},
        {"type":"view","name":"经纪人注册","url":"'.$WEBSITEDIR.'/gz/jingjiren.jpg"},
		{"type":"view","name":"商城规则","url":"'.$WEBSITEDIR.'/gz/guize.jpg"},
        ]},{"name":"至尊商城","type":"view","url":"'.$domain_url.$web_site_dir.'/oauth2?organization_code='.$organization_code.'"},
        {"name":"服务中心","type":"view","url":"http://www.zzytrade.com/qrcode/zaixianzixun/"}
        ]}';*/
		
		
		$data = '{"button":[{"name":"云商城","type":"view","url":"'.$domain_url.$web_site_dir.'/oauth2?organization_code='.$organization_code.'"},
		{"name":"交易指南","sub_button":[
        {"type":"view","name":"注册流程","url":"'.$domain_url.$web_site_dir.$shopping.'/gz/zhuce.jpg"},
        {"type":"view","name":"提现流程","url":"'.$domain_url.$web_site_dir.$shopping.'/gz/tixian.jpg"},
        {"type":"view","name":"充值流程","url":"'.$domain_url.$web_site_dir.$shopping.'/gz/chongzhi.jpg"},
        {"type":"view","name":"经纪人注册","url":"'.$domain_url.$web_site_dir.$shopping.'/gz/jingjiren.jpg"},
		{"type":"view","name":"商城规则","url":"'.$domain_url.$web_site_dir.$shopping.'/gz/guize.jpg"}
        ]},
		 {"name":"在线客服","type":"view","url":"'.$domain_url.$web_site_dir.$shopping.'/gz/kefu_online.jpg"}
        ]}';
		
		
		
		
		$res = $this->api_notice_increment($url, $data);

        $menu = json_decode($res, true);
        $flag = false;
        if ($menu['errcode'] == "45009") {
            if ($flag == true) {
                $data = '{"appid":"'.$appid.'"}';
                $url = "https://api.weixin.qq.com/cgi-bin/clear_quota?access_token=".$access_token;
                $res = $this->api_notice_increment($url, $data);
            }
            $path = "C:/HwsApacheMaster/wwwroot/maijiyi_8KxId5/log/wx/";
            if (!is_dir($path)){
                mkdir($path,0777);  // 创建文件夹test,并给777的权限（所有权限）
            }
            $file = $path.'wx_info.txt';    // 写入的文件
            $log = "--------access_token:".$access_token."-------rel：".$res;
            file_put_contents($file,$log,FILE_APPEND);
        } else {
            echo $menu['errmsg'];
        }
    }

    // 验证TOKEN
    private function valid($echostr, $signature, $nonce, $timestamp) {
        if($this->checkSignature($signature, $nonce, $timestamp)){
            header('content-type:text');
            echo $echostr;
            exit;
        }
    }

    // 验证TOKEN标签
    private function checkSignature($signature, $nonce, $timestamp) {
        $tmpArr = array($this->token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }

    private function getAccess_token($organization_code, &$appid="", &$appsecret="") {
        $where['_string'] = "concat(b.p_code,b.level,b.code)='".$organization_code."'";
        $left = "left join fs_organization b on b.id = a.organization_id and a.state = 1";
        $organizationSetting = OrganizationSettingApi::getInfoByCondition($where, $left, "a.id, a.wx_appid, a.wx_secret, a.access_token, ifnull(a.expires_in, 0) expires_in, a.refresh_time");

        $access_token = $organizationSetting['access_token'];
        $expires_in = $organizationSetting['expires_in'];
        $refresh_time = strtotime($organizationSetting['refresh_time']);
        $current_time = strtotime(date('Y-m-d H:i:s'));
        $appid=$organizationSetting['wx_appid'];
        $appsecret=$organizationSetting['wx_secret'];

        if (empty($access_token) || ($current_time-$refresh_time) > $expires_in) {
            $access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
            $res = $this->https_request($access_token_url);
            $token = json_decode($res, true);
            if (!isset($token["errcode"])) {
                $access_token = $token['access_token'];
                $organizationSetting['access_token'] = $access_token;
                $organizationSetting['expires_in'] = $token['expires_in'];
                $organizationSetting['refresh_time'] = date('Y-m-d H:i:s');
                OrganizationSettingApi::save($organizationSetting);
            }
        }

        return $access_token;
    }

    private function getOpenid($appid, $appsecret, $code) {
        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
        $res = $this->https_request($get_token_url);
        $openid = json_decode($res, true);
        return $openid['openid'];
    }

    private function getUserInfo($access_token, $openid) {
        //根据openid和access_token查询用户信息
        $get_user_info_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
        $res = $this->https_request($get_user_info_url);
        return $res;
    }

    private function getJsApiTicket($access_token) {
        $get_user_info_url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access_token.'&type=jsapi';
        $res = $this->https_request($get_user_info_url);
        $access_token = json_decode($res, true);
        return $access_token['ticket'];
    }

    private function https_request($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {return 'ERROR '.curl_error($curl);}
        curl_close($curl);
        return $data;
    }

    private function api_notice_increment($url, $data) {
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            curl_close($ch);
            return $ch;
        } else {
            curl_close($ch);
            return $tmpInfo;
        }
    }

    // 生成邀请码
    private function generate_invite_code($len) {
        $strs = rand_number(1, $len);
        if ($this->check_code($strs)) {
            $modelObj = M('user');
            $result = $modelObj->where(array('code' => $strs))->select();
            if (count($result) == 0) {
                return $strs;
            } else {
                return rand_number(1, $len);
            }
        } else {
            return rand_number(1, $len);
        }
    }

    // 检验邀请码
    private function check_code($str){
        $isok = true;
        $z = 5;
        for($i=0;$i<=5;$i++){
            $five="";
            $x = 0;
            for ($j=$z;$j>0;$j--) {
                $five = $five.$str{$i+$x};
                $x++;
            }
            $z--;
            $now_chong = $str{$i}.$str{$i}.$str{$i}.$str{$i}.$str{$i};
            $now_zeng = $str{$i}.chr(ord($str{$i})+1).chr(ord($str{$i})+2).chr(ord($str{$i})+3).chr(ord($str{$i})+4);
            if($five==$now_chong){
                $isok = false;
                break;
            }elseif($five==$now_zeng){
                $isok = false;
                break;
            }
        }
        if($isok){
            return true;
        }else{
            return false;
        }
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}